package ytdp.careagle.com.ytdp.activity;

import android.Manifest;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.dplus.UMADplus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import ytdp.careagle.com.ytdp.R;
import ytdp.careagle.com.ytdp.adapter.FragmentBannerAdapter;
import ytdp.careagle.com.ytdp.app.APP;
import ytdp.careagle.com.ytdp.app.G;
import ytdp.careagle.com.ytdp.app.manager.ImageLoadManager;
import ytdp.careagle.com.ytdp.entity.ModelRelationship;
import ytdp.careagle.com.ytdp.entity.ProvinceEntity;
import ytdp.careagle.com.ytdp.entity.ValuationQuery;
import ytdp.careagle.com.ytdp.entity.VehicleSeries;
import ytdp.careagle.com.ytdp.fragment.FragmentBanner;
import ytdp.careagle.com.ytdp.mvp.presenter.CarEvaluatePresenter;
import ytdp.careagle.com.ytdp.mvp.view.ICarEvaluateView;
import ytdp.careagle.com.ytdp.myview.CameraSurfaceView;
import ytdp.careagle.com.ytdp.myview.MyEditText;
import ytdp.careagle.com.ytdp.myview.MyKeyboradView;
import ytdp.careagle.com.ytdp.myview.SelectAddressView;
import ytdp.careagle.com.ytdp.myview.SelectTimeView;
import ytdp.careagle.com.ytdp.utils.camer_util.EventUtil;
import ytdp.careagle.com.ytdp.utils.camer_util.GoogleFaceDetect;

public class CarEvaluateQueryActivity extends BaseActivity implements View.OnFocusChangeListener, ICarEvaluateView, ViewPager.OnPageChangeListener, MyKeyboradView.KeyBoardListener, SelectTimeView.SelecedListener, SelectAddressView.SelecedListener {

    private static final int ADDRESS = 1;
    private static final int SELECT_TIME = 2;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_subtitle)
    TextView tvSubtitle;
    @Bind(R.id.tv_location)
    TextView tvLocation;
    @Bind(R.id.tv_car_model)
    TextView tvCarModel;
    @Bind(R.id.tv_select_car_model)
    TextView tvSelectCarModel;
    @Bind(R.id.tv_car_type)
    TextView tvCarType;
    @Bind(R.id.iv_time_reg)
    ImageView ivTimeReg;
    @Bind(R.id.tv_time_reg)
    TextView tvTimeReg;
    @Bind(R.id.tv_select_time_reg)
    TextView tvSelectTimeReg;
    @Bind(R.id.iv_mileage)
    ImageView ivMileage;
    @Bind(R.id.et_mileage)
    MyEditText etMileage;
    @Bind(R.id.tv_select_mileage)
    TextView tvSelectMileage;
    @Bind(R.id.ll_car_info)
    LinearLayout llCarInfo;
    @Bind(R.id.vp_banner)
    ViewPager vpBanner;
    @Bind(R.id.tv_start_evaluate)
    TextView tvStartEvaluate;
    @Bind(R.id.ll_points)
    LinearLayout llPoints;
    @Bind(R.id.myKeyboradView)
    MyKeyboradView myKeyboradView;
    @Bind(R.id.layout_gen)
    ConstraintLayout layoutGen;
    @Bind(R.id.selectTimeView)
    SelectTimeView selectTimeView;
    @Bind(R.id.ll_selectAddressView)
    LinearLayout llSelectAddressView;
    @Bind(R.id.iv_gif)
    ImageView ivGif;
    @Bind(R.id.view_line)
    View viewLine;
    @Bind(R.id.ll_git)
    LinearLayout llGif;
    @Bind(R.id.ivFace)
    ImageView ivFace;
    private GoogleFaceDetect googleFaceDetect;
    private MainHandler mMainHandler;
    private MediaPlayer mPlayer;
    private String provinceName;
    private String provinceCode;
    private String cityName;
    private String cityCode;
    private int selectedColor;
    private ViewGroup.LayoutParams layoutParamsMileage;
    private ViewGroup.LayoutParams layoutParamsTime;
    private ValueAnimator valueAnimator;
    private CarEvaluatePresenter presenter;
    private ModelRelationship.ChildrenBean childrenBean;
    private boolean isAddress = false;//是否出入了地址信息
    private boolean isCarType = false;//是否输入了车型信息
    private boolean isFirstReg = false;//是否输入了首次上牌时间信息
    private boolean isFirstInit = true;//刚进入界面  第一次加载完成
    private int clickTimes = 0;//点击次数
    private int defaultColor;
    private ArrayList<ImageView> points;
    private int size;
    private String[] defaultAddress;
    private String[] defaultCodes;
    private SelectAddressView selectAddressView;
    private Disposable subscribe;
    private int[] welcomes = {R.raw.welcome_1, R.raw.welcome_2};
    private int oggIndex = 0;
    private String extension = "1";//1开启人脸识别0关闭人脸识别
    private CameraSurfaceView cameraSurfaceView;
    private int selectedLineColor;
    private static int VIEWPAGER_ENENT = 3;

    @OnClick({R.id.tv_location, R.id.tv_select_car_model, R.id.tv_start_evaluate,
            R.id.tv_select_time_reg, R.id.tv_select_mileage, R.id.tv_time_reg, R.id.tv_car_model,
            R.id.tv_car_type, R.id.iv_time_reg, R.id.tv_title, R.id.layout_gen, R.id.et_mileage, R.id.iv_mileage, R.id.iv_gif})
    public void onClick(View view) {
        APP.getInstance().resetCountDown();//从新跳转
        cancelReStartCamera();//取消15秒后开启人脸检测
        if (view.getId() != R.id.tv_select_mileage &&
                view.getId() != R.id.et_mileage &&
                view.getId() != R.id.iv_mileage) {
            myKeyboradView.closeKeyboard();
        }
        if (view.getId() != R.id.tv_select_time_reg
                && view.getId() != R.id.tv_time_reg
                && view.getId() != R.id.iv_time_reg) {
            selectTimeView.closed();
        }
        if (view.getId() != R.id.tv_location && selectAddressView != null) {
            selectAddressView.closed();
        }
        closeGif();
        switch (view.getId()) {
            case R.id.tv_location:
                getCityData();
                break;
            case R.id.tv_car_type:
            case R.id.tv_select_car_model:
            case R.id.tv_car_model:
                startActivity(new Intent(this, SelectCarBrandActivity.class));
                break;
            case R.id.tv_start_evaluate:
                if (!isCarType) {
                    showMessage("请选择车型");
                } else if (!isFirstReg) {
                    showMessage("请输入首次上牌时间");
                } else if (!isAddress) {
                    showMessage("请选择地址");
                } else if (TextUtils.isEmpty(etMileage.getText().toString())) {
                    showMessage("请输入里程数");
                } else {
                    presenter.startEvaluate(getWContext().get());
                }
                break;
            case R.id.tv_time_reg:
            case R.id.iv_time_reg:
            case R.id.tv_select_time_reg:
                if (layoutParamsTime.height == 0) {
                    tvTimeReg.setTextColor(selectedLineColor);
                    tvTimeReg.setText("|");
                    tvSelectTimeReg.setText("上牌时间");
                    etSelect(tvSelectTimeReg);
                    startIconAnim(layoutParamsTime, ivTimeReg);
                }
                selectTime();
                break;
            case R.id.tv_select_mileage:
                if (etMileage.isFocused()) {
                    return;
                }
                myKeyboradView.getFocus(etMileage, etMileage);
                break;
            case R.id.tv_title://点击爱车估值（三次后会出现退出登录页面）
                clickThreeTimes();
                break;
            default:
                break;
        }
    }

    private void clickThreeTimes() {
        clickTimes++;
        if (clickTimes == 3) {
            getOperation().forward(LogoutActivity.class);
        }
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 2000);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            clickTimes = 0;
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_car_evaluate_query;
    }

    @Override
    public void initView() {
        defaultColor = getResources().getColor(R.color.text_gray);
        selectedColor = getResources().getColor(R.color.text_title);
        selectedLineColor = getResources().getColor(R.color.guestPaint_color_wrong);
        layoutParamsMileage = ivMileage.getLayoutParams();
        layoutParamsMileage.height = 0;
        ivMileage.setLayoutParams(layoutParamsMileage);
        layoutParamsTime = ivTimeReg.getLayoutParams();
        layoutParamsTime.height = 0;
        ivTimeReg.setLayoutParams(layoutParamsTime);
        vpBanner.setPageMargin((int) getResources().getDimensionPixelOffset(R.dimen.dp10));
        vpBanner.setOnPageChangeListener(this);
        initInput();
        etMileage.setOnFocusChangeListener(this);
        EventBus.getDefault().register(this);
        presenter = new CarEvaluatePresenter(this);
        presenter.getBanner(getWContext().get());
        presenter.getBasicConfig(getWContext().get());
        myKeyboradView.setListener(this);
        selectTimeView.setListener(this);

        ImageLoadManager.getImageLoadManager().loadgif(ivGif, R.drawable.test_gif);
        HashMap<String, Object> map = new HashMap<>();
        map.put("估值", "haha");
        UMADplus.track(this, "估值页面", map);
        if (TextUtils.isEmpty(extension) || "1".equals(extension)) {
            new RxPermissions(CarEvaluateQueryActivity.this)
                    .request(Manifest.permission.CAMERA)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean aBoolean) {
                            try {
                                Camera camera = Camera.open(G.CAMERA_FRONT_OR_BACK);
                                camera.release();
                                camera = null;
                            } catch (Exception e) {
                                e.printStackTrace();
                                showMessage("没有相关摄像头，或没有摄像头权限");
                                return;
                            }
                            if (aBoolean) {
                                initFaceCheck();
                            } else {
                                showMessage("没有相关摄像头，或没有摄像头权限");
                            }
                        }
                    });
        }
    }

    private void initFaceCheck() {
        cameraSurfaceView = new CameraSurfaceView(this);
        int dimension = (int) getResources().getDimension(R.dimen.dp100);
        cameraSurfaceView.setLayoutParams(new ViewGroup.LayoutParams(dimension, dimension));
        layoutGen.addView(cameraSurfaceView);
        mMainHandler = new MainHandler();
        googleFaceDetect = new GoogleFaceDetect(getApplicationContext(), mMainHandler);
        mMainHandler.sendEmptyMessageDelayed(EventUtil.CAMERA_HAS_STARTED_PREVIEW, 1500);
    }

    private void initInput() {
        //禁止软键盘弹出
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        //顺序要先获取焦点的放最后
        myKeyboradView.setEdittext(etMileage, MyKeyboradView.KEYBOARD_STATE_NUMBER);
        myKeyboradView.setIsOpen(false);
    }

    private void selectTime() {
        int year = -1;
        int month = -1;
        String textTime = tvTimeReg.getText().toString();
        try {
            if (!TextUtils.isEmpty(textTime) && !textTime.equals("|") && textTime.contains("-")) {
                String[] split = textTime.split("-");
                year = Integer.valueOf(split[0]);
                month = Integer.valueOf(split[1]);
            }
        } catch (Exception e) {
        }
        selectTimeView.setSelected(year, month);
        selectTimeView.animate().translationYBy(selectTimeView.getTranslationY()).translationY(0).setDuration(200).start();
    }

    private void getCityData() {
        presenter.getCityData(getWContext().get());
    }

    @Override
    public void selectCity(Serializable provinceEntities) {
        if (selectAddressView == null) {
            selectAddressView = new SelectAddressView(this, provinceName, cityName, (List<ProvinceEntity>) provinceEntities);
            selectAddressView.setListener(this);
            llSelectAddressView.addView(selectAddressView);
        }
        selectAddressView.open();
//        Intent intent = new Intent(CarEvaluateQueryActivity.this, SelectProvinceDialog.class);
//        intent.putExtra("data", provinceEntities);
//        intent.putExtra("provinceName", provinceName);
//        intent.putExtra("cityName", cityName);
//        int bottom = llCarInfo.getBottom();
//        intent.putExtra("bottom", bottom);
//        startActivityForResult(intent, ADDRESS);
    }

    @Override
    public ModelRelationship.ChildrenBean getCarModel() {
        return childrenBean;
    }

    @Override
    public String getMileage() {
        return etMileage.getText().toString();
    }

    @Override
    public String getCityCode() {
        return cityCode;
    }

    @Override
    public String getFirstRegDate() {
        return tvTimeReg.getText().toString();
    }

    @Override
    public String getProvinceCode() {
        return provinceCode;
    }

    @Override
    public String getCityName() {
        return cityName;
    }

    @Override
    public String getProvinceName() {
        return provinceName;
    }

    @Override
    public void loadSuccess(ValuationQuery data) {
        String firstRegDate = getFirstRegDate();
        String[] split = firstRegDate.split("-");
        if (Integer.valueOf(split[1]) < 10) {
            firstRegDate = split[0] + "-0" + split[1];
        }
        Intent intent = new Intent(this, EvaluateResultActivity.class);
        intent.putExtra("data", data);
        intent.putExtra("modelCode", childrenBean.getCode());
        intent.putExtra("mileage", getMileage());
        intent.putExtra("cityCode", cityCode);
        intent.putExtra("firstRegDate", firstRegDate);
        intent.putExtra("purchasePrice", data.getPurchasePrice() + "");
        intent.putExtra("modelName", childrenBean.getName());
        intent.putExtra("carSeriesCode", childrenBean.getSeriesCode());
        intent.putExtra("carSeriesName", childrenBean.getSeriesName());
        intent.putExtra("brandCode", childrenBean.getBrandCode());
        intent.putExtra("brandName", childrenBean.getBrandName());
        intent.putExtra("provinceCode", provinceCode);
        intent.putExtra("provinceName", provinceName);
        intent.putExtra("cityName", cityName);
        if (!TextUtils.isEmpty(childrenBean.getImageUrl())) {
            intent.putExtra("imageUrl", childrenBean.getImageUrl());
        } else {
            intent.putExtra("imageUrl", "");
        }
        startActivity(intent);
    }

    @Override
    public void setData(List<VehicleSeries> vehicleSeries) {
        ArrayList<FragmentBanner> list = new ArrayList<>();
        //如果是单数  就再加一条
        if (vehicleSeries.size() % 2 != 0) {
            vehicleSeries.add(vehicleSeries.get(0));
        }
        size = vehicleSeries.size() / 2;
        try {
            for (int i = 0; i < size; i++) {
                FragmentBanner fragmentBanner = new FragmentBanner();
                Bundle bundle = new Bundle();
                bundle.putSerializable("item1", vehicleSeries.get(i * 2 + 0));
                bundle.putSerializable("item2", vehicleSeries.get(i * 2 + 1));
                fragmentBanner.setArguments(bundle);
                list.add(fragmentBanner);
            }
        } catch (Exception e) {
            Log.e("tag", e.getMessage());
        }
        FragmentBannerAdapter bannerAdapter = new FragmentBannerAdapter(getSupportFragmentManager(), list);
        vpBanner.setAdapter(bannerAdapter);
        points = new ArrayList<>();
        int dp5 = (int) getResources().getDimension(R.dimen.dp2);
        for (int i = 0; i < size; i++) {
            ImageView point = new ImageView(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dp5, dp5);
            layoutParams.leftMargin = dp5;
            layoutParams.rightMargin = dp5;
            point.setImageResource(R.drawable.selector_banner_point);
            point.setLayoutParams(layoutParams);
            points.add(point);
            if (i == 0) {
                point.setSelected(true);
            }
            llPoints.addView(point);
        }
        initViewPagerTimer();
    }

    private int pageIndex = 0;

    private Handler mVPHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            pageIndex = vpBanner.getCurrentItem();
            pageIndex++;
            vpBanner.setCurrentItem(pageIndex % points.size());
            super.handleMessage(msg);
        }
    };

    private void initViewPagerTimer() {
        mVPHandler.sendEmptyMessageDelayed(VIEWPAGER_ENENT, 5000);
//        // timer 默认在新线程，所以需要切换回主线程
//        if (subscribe == null && points.size() > 1) {
//            subscribe = Observable.interval(5, 5, TimeUnit.SECONDS)
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread()) // timer 默认在新线程，所以需要切换回主线程
//                    .subscribe(new Consumer<Long>() {
//                        @Override
//                        public void accept(@NonNull Long aLong) throws Exception {
//                            pageIndex = vpBanner.getCurrentItem();
//                            pageIndex++;
//                            vpBanner.setCurrentItem(pageIndex % points.size());
//                        }
//                    });
//        }
    }

    @Override
    public void setCity(String s) {
        tvLocation.setText(s);
    }

    @Override
    public void setCityData(String[] codes, String[] address) {
        defaultCodes = codes;
        defaultAddress = address;

        provinceCode = codes[0];
        cityCode = codes[1];
        provinceName = address[0];
        cityName = address[1];
        isAddress = true;
        setCity(cityName);
    }

    @Override
    public void setFaceCheck(String extension) {
        this.extension = extension;
    }

    private void etSelect(TextView textView) {
        textView.setTextColor(getResources().getColor(R.color.text_gray));
        mySetTextSize(textView, 10);
    }

    private void startIconAnim(final ViewGroup.LayoutParams layoutParams, final View view) {
        valueAnimator = ValueAnimator.ofFloat(0, getResources().getDimension(R.dimen.dp15));
        valueAnimator.setDuration(1000);
        valueAnimator.setInterpolator(new BounceInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (Float) animation.getAnimatedValue();
                layoutParams.height = (int) value;
                view.setLayoutParams(layoutParams);
            }
        });
        valueAnimator.start();
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        APP.getInstance().resetCountDown();
        if (b && layoutParamsMileage.height == 0) {
            myKeyboradView.show(etMileage);
            if (selectAddressView != null) {
                selectAddressView.closed();
            }
            if (selectTimeView != null) {
                selectTimeView.closed();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (valueAnimator != null && valueAnimator.isRunning()) {
            valueAnimator.cancel();
        }
        if (mMainHandler != null) {
            mMainHandler.removeMessages(0);
            mMainHandler.removeMessages(1);
        }
        if (mVPHandler != null) {
            mVPHandler.removeMessages(VIEWPAGER_ENENT);
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getCarType(ModelRelationship.ChildrenBean childrenBean) {
        tvCarType.setText(childrenBean.getName());
        tvCarType.setVisibility(View.VISIBLE);
        tvCarModel.setVisibility(View.GONE);
        tvSelectCarModel.setVisibility(View.GONE);
        isCarType = true;
        this.childrenBean = childrenBean;
    }

    //页面恢复初始状态
    public void reSetUi() {
        isAddress = false;
        isFirstReg = false;
        isCarType = false;
        //地址重置
        if (defaultCodes != null) {
            setCityData(defaultCodes, defaultAddress);
        } else {
            tvLocation.setText("选择车辆所在地");
        }
        //车型重置
        tvCarType.setVisibility(View.GONE);
        tvCarModel.setVisibility(View.VISIBLE);
        tvSelectCarModel.setVisibility(View.VISIBLE);
        //里程数 和 时间重置
        layoutParamsMileage = ivMileage.getLayoutParams();
        layoutParamsMileage.height = 0;
        ivMileage.setLayoutParams(layoutParamsMileage);
        layoutParamsTime = ivTimeReg.getLayoutParams();
        layoutParamsTime.height = 0;
        ivTimeReg.setLayoutParams(layoutParamsTime);

        tvTimeReg.setText("上牌时间");
        tvTimeReg.setTextColor(defaultColor);

        tvSelectTimeReg.setText("请选择");
        tvSelectTimeReg.setTextColor(selectedColor);
        mySetTextSize(tvSelectTimeReg, 14);

        etMileage.setHint(getResources().getString(R.string.mileage_hint_default));
        etMileage.setText("");
        mySetTextSize(tvSelectMileage, 14);
        tvSelectMileage.setText("请选择");
        tvSelectMileage.setTextColor(selectedColor);

        myKeyboradView.closeKeyboard();
    }

    //TODO 在大屏上时*2   手机测试不变
    private void mySetTextSize(TextView textView, int size) {
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, size * 2);
    }

    @Override
    public void showKeyBoard() {
        startIconAnim(layoutParamsMileage, ivMileage);
        etMileage.setHint(getResources().getString(R.string.mileage_hint));
        tvSelectMileage.setText("行驶里程（公里）");
        etSelect(tvSelectMileage);
        if (myKeyboradView != null) {
            myKeyboradView.closeKeyboard();
        }
        if (selectAddressView != null) {
            selectAddressView.closed();
        }
        if (selectTimeView != null) {
            selectTimeView.closed();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (isFirstInit) {
            isFirstInit = false;
            myKeyboradView.setTranslationY(2 * myKeyboradView.getHeight());
            selectTimeView.setTranslationY(2 * selectTimeView.getHeight());
            llGif.setTranslationY(-G.height);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        if (points != null && points.size() > 1) {
            for (ImageView point : points) {
                point.setSelected(false);
            }
            points.get(position).setSelected(true);
        }
        mVPHandler.removeMessages(VIEWPAGER_ENENT);
        mVPHandler.sendEmptyMessageDelayed(VIEWPAGER_ENENT, 5000);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && myKeyboradView.getTranslationY() == 0) {
            myKeyboradView.closeKeyboard();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void reSetCamera() {
        if ("0".equals(extension)) {
            return;
        }
        mMainHandler.sendEmptyMessageDelayed(EventUtil.CAMERA_HAS_STARTED_PREVIEW, 1500);

    }

    @Override
    public void selected(String yearSelected, String monthSelected) {
        isFirstReg = true;
        tvTimeReg.setTextColor(selectedColor);
        tvTimeReg.setText(yearSelected + "-" + monthSelected);
//        String yearSelected = b.getString("yearSelected");
//        String monthSelected = b.getString("monthSelected");

    }

    @Override
    public void selected(String provinceName, String provinceCode, String cityName, String cityCode) {
        this.provinceName = provinceName;
        this.provinceCode = provinceCode;
        this.cityName = cityName;
        this.cityCode = cityCode;
        tvLocation.setText(cityName);
        isAddress = true;
    }

    private class MainHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case EventUtil.UPDATE_FACE_RECT:
                    stopGoogleFaceDetect();
                    Log.e("face", "检测到人脸");
                    player();//播放欢迎提示音
                    break;
                case EventUtil.CAMERA_HAS_STARTED_PREVIEW:
                    startGoogleFaceDetect();
                    break;
                case 3:
                    closeGif();
                    break;
            }
            super.handleMessage(msg);
        }
    }

    private void closeGif() {
        llGif.animate().translationYBy(llGif.getTranslationY()).translationY(-G.height).setDuration(500).start();
    }

    private void player() {
        if ("0".equals(extension)) {
            return;
        }
        oggIndex++;
        mPlayer = MediaPlayer.create(this, welcomes[oggIndex % 2]);
        mPlayer.setLooping(false);
        mPlayer.start();
        mMainHandler.sendEmptyMessageDelayed(EventUtil.CAMERA_HAS_STARTED_PREVIEW, 15000);
        llGif.animate().translationYBy(llGif.getTranslationY()).setInterpolator(new OvershootInterpolator()).translationY(0).setDuration(500).start();
        mMainHandler.sendEmptyMessageDelayed(3, 5000);//5秒后关闭动画
    }

    public void cancelReStartCamera() {
        if ("0".equals(extension)) {
            return;
        }
        mMainHandler.removeMessages(EventUtil.CAMERA_HAS_STARTED_PREVIEW);
    }

    private void startGoogleFaceDetect() {
        if ("0".equals(extension)) {
            return;
        }
        try {
            Camera.Parameters params = cameraSurfaceView.getCamera().getParameters();
            if (params.getMaxNumDetectedFaces() > 0) {
                cameraSurfaceView.getCamera().setFaceDetectionListener(googleFaceDetect);
            }
            cameraSurfaceView.getCamera().startFaceDetection();
        } catch (Exception e) {
            Log.e("face", e.getMessage());
            showMessage("error: " + e.getMessage() + " max = " + cameraSurfaceView.getCamera().getParameters().getMaxNumDetectedFaces());
        }

    }

    private void stopGoogleFaceDetect() {
        if (extension.equals("0")) {
            return;
        }
        try {
            Camera.Parameters params = cameraSurfaceView.getCamera().getParameters();
            if (params.getMaxNumDetectedFaces() > 0) {
                cameraSurfaceView.getCamera().setFaceDetectionListener(null);
                cameraSurfaceView.getCamera().stopFaceDetection();
//            faceView.clearFaces();
            }
        } catch (Exception e) {

        }

    }
}
